#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from xpy3lib.XRetryableQuery import XRetryableQuery
from xpy3lib.LoggableObject import LoggableObject
from xpy3lib.XSingletonMeta import XSingletonMeta
from xpy3lib.XLogger import XLogger

class SD4C2(metaclass=XSingletonMeta):
    """

    """
    success = False
    df_range_4_all = None

    def __init__(self, p_db_conn=None, p_dataframe=None):
        if p_dataframe is None:
            sql = " SELECT " \
                  " FIELD_LG,M_CENT," \
                  " SPEC_BZ," \
                  " RANGE_N," \
                  " RANGE_COD," \
                  " PROD1," \
                  " LOWER_V," \
                  " SUPER_V " \
                  " FROM " \
                  " BGRAGGCB.WH_JH00_ZSPEC2" \
                  " WHERE 1=1 "
            XLogger.getInstance().logger.info(sql)
            df = XRetryableQuery(p_db_conn=p_db_conn, p_sql=sql, p_max_times=5).redo()
            df.columns = df.columns.str.upper()
            success = df.empty is False

            self.df_range_4_all = df
            self.success = success
        else:
            self.df_range_4_all = p_dataframe
            self.success = True

    def get_all_c2_by(self, p_spec_bz=None, p_m_cent=None, p_qs_code=None):
        """
        :param p_spec_bz:
        :param p_m_cent:
        :param p_qs_code:
        :return: success, field_lg_property
        """
        if self.success is False:
            return False, None

        df = self.df_range_4_all
        # t = df.loc[(df['SPEC_BZ'] == p_spec_bz)
        #            & (df['M_CENT'] == p_m_cent)
        #            & ( (df['PROD1'] == p_qs_code) | (df['PROD1'] is None) )]
        # t = df[(df['SPEC_BZ'] == p_spec_bz)
        #            & (df['M_CENT'] == p_m_cent)
        #            & (df['PROD1'] == p_qs_code)]
        t = df[
            (df['SPEC_BZ'] == p_spec_bz) & (df['M_CENT'] == p_m_cent) ]

        success = t.empty is False
        XLogger.getInstance().logger.info(success)
        if success is False:
            return False, None

        t = t.reset_index()
        field_lg_property = t.loc[0, 'FIELD_LG']
        return True, field_lg_property

    def get_matched_c2_by(self, p_spec_bz=None, p_m_cent=None, p_qs_code=None, p_field_lg_value=None):
        """
        :param p_spec_bz:
        :param p_m_cent:
        :param p_qs_code:
        :param p_field_lg_value:
        :return: success, row, field_lg_property(name, not value), range_cod, range_n
        """
        success, field_lg_property = self.get_all_c2_by(p_spec_bz=p_spec_bz, p_m_cent=p_m_cent, p_qs_code=p_qs_code)
        if success is False:
            return False, None, None, '', ''
        #
        t = (False, None, field_lg_property, '', '')
        df = self.df_range_4_all
        df1 = df[
            (df['SPEC_BZ'] == p_spec_bz) & (df['M_CENT'] == p_m_cent) ]
        df1 = df1.reset_index()
        if field_lg_property is not None:
            for index, row in df1.iterrows():
                if p_field_lg_value >= float(row['LOWER_V']) and p_field_lg_value < float(row['SUPER_V']):
                    t = (True, row, field_lg_property, row['RANGE_COD'], row['RANGE_N'])
                    break
        return t


"""
class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Cls4(metaclass=Singleton):
    pass

cls1 = Cls4()
cls2 = Cls4()
XLogger.getInstance().logger.info(id(cls1) == id(cls2))
"""